<template>
  <el-upload action="#" class="y-text-[0px] y-leading-[0px]" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="httpRequest">
    <div ref="yyUploadImgRef" class="y-inline-block y-border-[1px] y-rounded y-border-dashed y-border-gray-400  y-w-16 y-h-16 md:y-w-20 md:y-h-20 lg:y-w-32 lg:y-h-32">
      <el-image class="y-w-full y-h-full" v-if="formData" :src="formData" fit="cover"></el-image>
      <i v-else class="el-icon-plus hover:y-bg-gray-50 y-w-full y-h-full !y-flex y-justify-center y-items-center y-text-base md:y-text-xl lg:y-text-2xl y-text-gray-400 !y-font-bold"></i>
    </div>
  </el-upload>
</template>

<script>
import { imgTypeOptions } from "@/constant/defaultOptions.js";
import { createLoading, createMessage } from "@/utils/index.js";
export default {
  props: {
    value: {
      type: String,
      default: "",
    },
  },
  name: "yyUploadImg",
  computed: {
    formData: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("input", val);
      },
    },
  },
  data() {
    return {};
  },
  methods: {
    async httpRequest(raw) {
      const form = new FormData();
      form.append("file", raw.file);
      const loading = createLoading("上传中", this.$refs.yyUploadImgRef, {
        customClass: `[&>.el-loading-spinner>.circular]:y-w-6
        [&>.el-loading-spinner>.circular]:y-h-6
        [&>.el-loading-spinner>.el-loading-text]:y-text-xs
        lg:[&>.el-loading-spinner>.circular]:y-w-12
        lg:[&>.el-loading-spinner>.circular]:y-h-12
        lg:[&>.el-loading-spinner>.el-loading-text]:y-text-base`
      });
      try {
        const res = await this.$globalApi.login.uploadImgApi(form);
        this.formData = res.path;
      } catch (err) {
        console.log("上传头像失败了", err);
      } finally {
        loading.close();
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = imgTypeOptions.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        createMessage(`上传头像图片必须是${imgTypeOptions.join("、")}格式!`);
        return false;
      }
      if (!isLt2M) {
        createMessage(`上传头像图片大小不能超过 2MB!`);
        return false;
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style>
</style>